package com.grj.order.service;

import com.grj.common.model.OrderOutbox;
import com.grj.order.repository.OutboxRepository;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ganru
 * @date 2025/10/19 5:49
 */
@Component
public class OutboxPublisher {
    private final OutboxRepository outboxRepository;
    private final KafkaTemplate<String, String> kafkaTemplate;

    public OutboxPublisher(OutboxRepository outboxRepository, KafkaTemplate<String, String> kafkaTemplate) {
        this.outboxRepository = outboxRepository;
        this.kafkaTemplate = kafkaTemplate;
    }

    // 每 2 秒轮询一次（根据吞吐调节）
    @Scheduled(fixedDelay = 2000)
    public void pollAndPublish() {
        List<OrderOutbox> list = outboxRepository.findTop100BySentFalseOrderByCreatedAtAsc();
        for (OrderOutbox o : list) {
            try {
                // send synchronously to ensure success (也可以异步并在回调里 markSent)
                kafkaTemplate.send(o.getEventType(), o.getAggregateId(), o.getPayload()).get();
                // 标记为已发送（这里可以用 repository 修改）
                outboxRepository.markSent(o.getId());
            } catch (Exception e) {
                // 记录日志并跳过（下次继续重试）
                System.err.println("Outbox send failed id=" + o.getId() + " err=" + e.getMessage());
            }
        }
    }
}